<?php
namespace app\common\controller;
use app\common\model\Setup as SetupModel;
use app\common\model\AdminUser as AdminUserModel;

use app\api\controller\Weixin;
use org\Auth;
use think\Loader;
use think\Controller;
use think\Cookie;
use think\Db;
use think\Session;

/**
 * 前台公用基础控制器
 * Class AdminWapBase
 * @package app\common\controller
 */
class AdminWapBase extends Controller
{
    protected $setup_model;
    protected $admin_user_model;
    protected function _initialize()
    {
        parent::_initialize();
        $this->setup_model                    = new SetupModel();
        $this->admin_user_model               = new AdminUserModel();

        if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
            session('scope' , $this->request->param('scope' , null));
            if(!session('openid')) {
                $code = $this->request->param('code' , null);
                $state = $this->request->param('state' , null);
                if( $code && $state === cookie('state') ) {
                    $this->getInfo();
                }
                else {
                    $this->redir();
                }
            }
        }
        $this->getSetup();
        $this->getUser();

        // 输出当前请求控制器（配合后台侧边菜单选中状态）
        $this->assign('controller', Loader::parseName($this->request->controller()));
    }

    /**
     * 获取预约项目菜单
     */
    protected function getSetup()
    {
        $setup   = $this->setup_model->find(1);
        $this->assign('setup', $setup);
    }

    /**
     * 获取登录管理员信息
     */
    protected function getUser()
    {
        //账号openid识别
        if(Session('openid')){
            $admin_user = $this->admin_user_model->where('openid',Session('openid'))->find();
            if($admin_user){
                Session::set('admin_id',$admin_user['id']);
                Session::set('admin_cid',$admin_user['cid']);
            }
        }
        //账号非openid识别
        $admin_user = [];
        if(Session('admin_id')){
            $admin_user = $this->admin_user_model->find(Session('admin_id'));
            if($admin_user){
                Session::set('admin_id',$admin_user['id']);
                Session::set('admin_cid',$admin_user['cid']);
            }else{
                Session::delete('admin_id');
                Session::delete('admin_cid');
            }
        }
        $this->assign('admin_user', $admin_user);
    }

    //oauth跳转
    private function redir()
    {
        $url = $this->request->url(true);
        cookie('state' , rand(100000 , 999999));
        $Weixin = new Weixin();
        $scope = 'snsapi_userinfo';//授权
        $result = $Weixin->get_oauth_redirect($url , cookie('state') , $scope);
        $this->redirect($result);
    }

    /**
     * 获取用户信息
     * @author zlbao<276363733@QQ.com>
     * @date   : 2018/7/7/007
     */
    private function getInfo()
    {
        $Weixin = new Weixin();
        $result = $Weixin->get_oauth_accesstoken();
        //var_dump($result);
        if( $result['access_token'] && $result['openid'] ) {
            //获取用户信息
            $info = $Weixin->get_user_info($result['access_token'] , $result['openid'] , 'zh_CN');
            if (isset($info['openid'])==false) {
                die('获取用户信息失败');
            }else{
                session('openid' , $info['openid']);
            }
            $this->_url_replace();
        }
        else {
            echo('授权失败，重新授权！');
            $this->_url_replace();
        }
    }

    /** 将微信网页授权后的参数剔除掉 */
    function _url_replace()
    {
        if( $this->request->param('code') && $this->request->param('state') ) {
            $url = $this->request->url(true);
            $reg = '/\?code.*&state.*$/';
            $url = preg_replace($reg , '' , $url);
            $this->redirect($url);
        }
    }

    //文字特殊符号处理
    function replace_emoji($str){
        return preg_replace_callback('/[\xf0-\xf7].{3}/', function($r) { return '@E' . base64_encode($r[0]);}, $str);
    }



}